package Presentacion.ArticulosStock.ActualizaPreciosPorDescripcion;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import Logica.ArticulosStock.ABMArticulosLogica;
import Logica.ArticulosStock.ABMRubrosLogica;
import Logica.BaseDeDatos.ABMFamiliaLogica;
import Logica.Util.CalendarioPicker;
import Modelo.Articulo;
import Modelo.Familia;
import Modelo.Rubros;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.List;

public class ActualizaPreciosPorDescripcion extends JFrame {

	private JPanel contentPane;
	private JTextField tfBuscar;
	private JLabel lblPrecioFinal;
	private JTextField tfPrecioFinal;
	private JButton btnLimpiara, btnActualizaPrecios, btnFecha, btnBuscar;
	private JTable tabla;
	private JScrollPane scroll;
	private DefaultTableModel model;
	private JTextField tfFecha;
	
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ActualizaPreciosPorDescripcion frame = new ActualizaPreciosPorDescripcion();
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ActualizaPreciosPorDescripcion() {
		setResizable(false);
		setTitle("Actualizaci\u00F3n de precios por selecci\u00F3n");
		this.setVisible(true);

		/**Pregunto si al presionar la "X" esta seguro de que quiere cerrar la ventana.*/
		this.addWindowListener(new WindowAdapter() {
	           public void windowClosing(WindowEvent e) {
	        	   setDefaultCloseOperation(0); 
	        	   cerrarVentana();
	           }
	       });
		
		setBounds(100, 100, 750, 420);
		contentPane = new JPanel();
		contentPane.setBackground(new Color(192, 192, 192));
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JLabel lblBuscarArticulos = new JLabel("Buscar art\u00EDculos");
		lblBuscarArticulos.setFont(new Font("Tahoma", Font.BOLD, 14));
		lblBuscarArticulos.setBounds(10, 11, 267, 27);
		contentPane.add(lblBuscarArticulos);
		
		tfBuscar = new JTextField();
		tfBuscar.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent arg0) {
				if (arg0.getKeyCode() == KeyEvent.VK_ENTER) {
					filtrarTabla();
				}
			}
		});
		tfBuscar.addFocusListener(new FocusAdapter() {			
			public void focusGained(FocusEvent arg0) {
				pintaVerde(tfBuscar);
			}			
			public void focusLost(FocusEvent arg0) {
				pintaBlanco(tfBuscar);
			}
		});

		tfBuscar.setBounds(10, 39, 500, 25);
		contentPane.add(tfBuscar);
		tfBuscar.setColumns(10);
		tfBuscar.requestFocus();
		
		lblPrecioFinal = new JLabel("Precio final:");
		lblPrecioFinal.setFont(new Font("Tahoma", Font.BOLD, 14));
		lblPrecioFinal.setBounds(300, 75, 112, 27);
		contentPane.add(lblPrecioFinal);
		
		tfPrecioFinal = new JTextField();
		tfPrecioFinal.addFocusListener(new FocusAdapter() {			
			public void focusGained(FocusEvent arg0) {
				pintaVerde(tfPrecioFinal);
			}			
			public void focusLost(FocusEvent arg0) {
				pintaBlanco(tfPrecioFinal);
			}
		});
		tfPrecioFinal.setColumns(10);
		tfPrecioFinal.setBounds(410, 75, 100, 25);
		contentPane.add(tfPrecioFinal);
		
		btnLimpiara = new JButton("");
		btnLimpiara.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
			}
		});
		btnLimpiara.setIcon(new ImageIcon(ActualizaPreciosPorDescripcion.class.getResource("/Presentacion/Img/limpiar.png")));
		btnLimpiara.setToolTipText("Limpiar");
		btnLimpiara.setBounds(630, 39, 65, 65);
		contentPane.add(btnLimpiara);
		
		scroll = new JScrollPane();
		scroll.setBounds(10, 118, 724, 221);
		contentPane.add(scroll);
		
		tabla = new JTable();
		scroll.setViewportView(tabla);
		
		btnActualizaPrecios = new JButton("<<<< Actualiza los Precios >>>>");
		btnActualizaPrecios.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				
			}
		});
		btnActualizaPrecios.setBounds(210, 350, 322, 35);
		contentPane.add(btnActualizaPrecios);
		
		tfFecha = new JTextField();
		tfFecha.setEditable(false);
		tfFecha.setHorizontalAlignment(SwingConstants.CENTER);
		tfFecha.setBounds(10, 75, 100, 20);
		contentPane.add(tfFecha);
		tfFecha.setColumns(10);
		
		btnFecha = new JButton("...");
		btnFecha.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				
			}
		});
		btnFecha.setBounds(120, 75, 33, 23);
		contentPane.add(btnFecha);

		this.initTabla();
		this.getFechaCalendario(btnFecha, tfFecha);
		
		btnBuscar = new JButton("Buscar");
		btnBuscar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				filtrarTabla();
			}
		});
		btnBuscar.setBounds(519, 40, 89, 23);
		contentPane.add(btnBuscar);
	}
	
	public void initTabla(){
		model = new DefaultTableModel(
				new Object[][] {
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
						
					},
					new String[] {
						"Codigo", "Detalle", "Grupo/Distrib", "Familia", "Pr. Costo", "Pr. Venta", "Lista Rec", "Venta Act"
					}
				) {
					Class[] columnTypes = new Class[] {
						String.class, String.class, String.class, String.class, String.class, String.class, String.class, String.class
					};
					public Class getColumnClass(int columnIndex) {
						return columnTypes[columnIndex];
					}
					boolean[] columnEditables = new boolean[] {
						false, false, false, false, false, false, false, false
					};
					public boolean isCellEditable(int row, int column) {
						return columnEditables[column];
					}
				};
				
				tabla.setModel(model);
				tabla.getColumnModel().getColumn(0).setPreferredWidth(70);
				tabla.getColumnModel().getColumn(0).setMinWidth(40);
				tabla.getColumnModel().getColumn(1).setPreferredWidth(200);
				tabla.getColumnModel().getColumn(1).setMinWidth(150);
				tabla.getColumnModel().getColumn(2).setPreferredWidth(100);
				tabla.getColumnModel().getColumn(2).setMinWidth(60);				
	}
	
	public void cargaTabla(){		
//		model.setRowCount(0);
		this.initTabla();
		List<Articulo>list = ABMArticulosLogica.getList(tfBuscar.getText());
		Rubros r;
		Familia f;
		for (Articulo x : list) {
			r = ABMRubrosLogica.getById(x.getIdRubros());
			f = ABMFamiliaLogica.getById(x.getIdFamilia());
			model.addRow(new Object[] { 
					 x.getId(),		//Codigo
					 x.getNombre(),	//Detalle
					 r.getNombre(),	//Grupo/Distrib
					 f.getNombre(),	//Familia
					 x.getCosto(),	//Pr. Costo
					 x.getPrecio(),	//Pr. Venta
					 "",			//Lista Rec
					 ""				//Venta Act
					  
					 });
			 }		
	}
	
	/*Llamador del seleccionar fecha en calendario*/
	public void getFechaCalendario(JButton boton, final JTextField textfield){
	 final JFrame f = this;
	 boton.addActionListener(new ActionListener() {
	         public void actionPerformed(ActionEvent ae) {
	                textfield.setText(new CalendarioPicker(f).setPickedDate());
	               }
	         });
	 }
	
	
	/*Metodo para confirma si esta seguro que quiere cerrar la aplicacinn*/	
	public void cerrarVentana(){
					this.setVisible(false);					
	}
	
//  ** Pinto JTEXTFIELD de color   **  // 
  public void pintaVerde(JTextField tf){
		tf.setBackground(new Color(153, 255, 153));
	}
	
	public void pintaBlanco(JTextField tf){
		tf.setBackground(new Color(255, 255, 255));
	}
	
	private void filtrarTabla() {
		if (tfBuscar.getText().length() > 0){
			this.cargaTabla();
		}else
			this.initTabla();
		
        TableRowSorter<TableModel> modeloOrdenado = new TableRowSorter(model);
    	String fil = tfBuscar.getText();//.toLowerCase();
    	if (fil.length() != 0){    		
    		//anda perfecto con minuscula y mayuscula gracias al "(?i)".
    		modeloOrdenado.setRowFilter (RowFilter.regexFilter("(?i)"+fil+"*.")); 
        }else{//reestablezco la tabla original, buscando con vacio.
        	modeloOrdenado.setRowFilter (RowFilter.regexFilter(""));        	
    	}
    	tabla.setRowSorter (modeloOrdenado);    	
    }
}
